import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author liangzai
 * @Description:
 */
public class TcpEchoServer {
    private ServerSocket serverSocket = null;
    private ExecutorService executorService = Executors.newCachedThreadPool();

    public TcpEchoServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动!");
        while (true) {
            Socket cilentSocket = serverSocket.accept();
            executorService.submit(()->{
                try {
                    System.out.printf("客户端[%s : %d]上线!\n",cilentSocket.getInetAddress(),
                            cilentSocket.getPort());
                    processCilent(cilentSocket);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        }
    }

    private void processCilent(Socket cilentSocket) throws IOException {
        try(InputStream inputStream = cilentSocket.getInputStream();
            OutputStream outputStream = cilentSocket.getOutputStream()){
            Scanner scanner = new Scanner(inputStream);
            PrintWriter writer = new PrintWriter(outputStream);
            while (true) {
                String request = scanner.nextLine();
                String response = process(request);

                writer.println(response);
                writer.flush();
                System.out.printf("[%s : %d] req : %s, resp : %s\n",cilentSocket.getInetAddress(),
                        cilentSocket.getPort(),request,response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            System.out.printf("客户端[%s : %d]下线!\n",cilentSocket.getInetAddress(),
                    cilentSocket.getPort());
            cilentSocket.close();
        }
    }

    private String process(String request){
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer server = new TcpEchoServer(9090);
        server.start();
    }
}








